import type { CSSProperties } from 'vue';
import type { Color, Emptyable, Numberic, PtComponent, PtComponentConst, Sizeic, TextAlign } from "../../../types";
import type { PtContainer } from '../../../types';

export const name = 'table';

type ComponentType = typeof name;

export interface Props {
    // 数据集
    data: string;
    // 表格数据字段填充
    rows: string[][];
}

export interface RenderOptions {
    // 表格列宽
    columns: Emptyable<Sizeic, ''>[];
    // 样式
    border: boolean;
    borderColor: Color;
    background: string;
    textAlign: TextAlign;
    size: Numberic;
}

export interface ThisComponent extends PtComponent<ComponentType, Props, RenderOptions> {}

export const render = (instance: PtContainer, comp: ThisComponent | PtComponentConst): JSX.Element => {
    const { value, render } = comp;

    const tableData = instance.data.get(value.data) || [];
    const border = render.border ? `1px solid ${render.borderColor}` : '';

    const style: CSSProperties = {
        // 表格增加边框
        border,
        borderSpacing: 0,
        background: render?.background,
        textAlign: render?.textAlign || 'left',
        fontSize: instance.style.calcSize(render?.size || 14),
    }

    return (<table style={style}>
        {value.rows.map((row: string[], index: number) => {
            return (<tr>
                {row.map((cell: string) => {
                    const tdStyle = {
                        width: instance.style.calcSize(render.columns?.[index]),
                        border,
                    };

                    {if (cell.startsWith('.')) {
                        // 表格指定数据
                        return (<td style={tdStyle}>{tableData[index]?.[cell.slice(1)] || '-'}</td>)
                    } else {
                        // 数据集数据
                        return (<td style={tdStyle}>{instance.data.getString(cell) || '-'}</td>)
                    }}
                })}
            </tr>)
        })}
    </table>)
}